package cn.template.models.common;

import cn.template.enums.UserRole;
import cn.template.models.User;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
public class JwtUser implements UserDetails {
    private long id;
    private String username;
    private String password;
    private String name;
    private String tel;
    private String idNumber;
    private List<UserRole> userRoles;
    private long companyId;
    private String companyName;
    private boolean enabled;
    // for JSON serialize
    public JwtUser() {
    }

    public JwtUser(User user) {
        this.id= user.getId();
        this.username = user.getUsername();
        this.password = user.getPassword();
        this.name = user.getName();
        this.tel = user.getTel();
        this.idNumber = user.getIdNumber();
        this.userRoles = user.getUserRoles();
        this.companyId = user.getCompany().getId();
        this.companyName =user.getCompany().getName();
        this.enabled = true;
    }

    @Override
    @JsonIgnore
    public Collection<? extends GrantedAuthority> getAuthorities() {
        Collection<GrantedAuthority> collection = new ArrayList<>();
        for(UserRole role: this.userRoles) {
            collection.add(new SimpleGrantedAuthority(role.toString()));
        }
        return  collection;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    @JsonIgnore
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }
}